package com.zsrt.java.day20161227.wrl.homework.demo01;

import java.text.DecimalFormat;

import org.junit.Test;

public class RedEnvelope {
	
	/**
	 * 作业01：======================
	 * 发1元的红包 然后让2个人去抢   必做。 问题  前面红包大   小 判断   想想   0.00
	 */
	@Test
	public void redEnvelope01(){
		double money = 10.0;
		int people	 = 3;
		
		//设置保留2位小数
		DecimalFormat df = new DecimalFormat("0.00");
		double perMoney = 0;
		double moneySum = 0;
		for(int p = 1 ; p <= people-1; p++){
			perMoney = Math.random()*money;
//			System.out.println(df.format(perMoney));
			
			//计算前几个人红包金额的和
			moneySum = moneySum + perMoney;
			if(perMoney < money && moneySum < money){
				perMoney = Double.parseDouble(df.format(perMoney));
				System.out.println(perMoney);
			}else{
				moneySum = moneySum - perMoney;
				p--;
			}
		}
		System.out.println(df.format(money-moneySum));
	}
	
	/**
	 * 发红包
	 * @param money	钱
	 * @param people	红包个数
	 */
	@Test
	public static double[] redEnvelope02(double money,int people){
		
		//建立数组，保存红包
		double[] redEs = new double[people];
		
		//设置保留2位小数
		DecimalFormat df = new DecimalFormat("0.00");
		double perMoney = 0;
		double moneySum = 0;
		for(int p = 1 ; p < people; p++){
			perMoney = Math.random()*money;
			
			//前people-1个人的红包和
			moneySum = moneySum + perMoney;
			if(perMoney < money && moneySum < money){
				perMoney = Double.parseDouble(df.format(perMoney));
				
				//利用数组保存前people-1个人的红包
				redEs[p-1] = perMoney;
//				System.out.println(perMoney);
			}else{
				moneySum = moneySum - perMoney;
				p--;
			}
		}
//		System.out.println(df.format(moneySum));
		redEs[people-1] = Double.parseDouble(df.format(money-moneySum));
		return redEs;
	}
}
